﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Mod.Talks
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.enums;
    using System.Collections.Specialized;
    public partial class Threads : Classes.TalksPageBase
    {
        Sc_PostCategory _category;
        Guid _cid;
        protected int page;

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Request.QueryString["c"] == null)
            {
                RedirectToDefaultPage();
            }
            else
            {
                _cid = new Guid(Request.QueryString["c"]);
                _category = PostOperations.GetCategory(_cid);
                ltrTitle.Text = _category.CategoryName;
                ltrCategoryName.Text = _category.CategoryName;
                LinqDataSource1.Selecting += new EventHandler<LinqDataSourceSelectEventArgs>(LinqDataSource1_Selecting);
                lblBrowsing.PreRender += new EventHandler(lblBrowsing_PreRender);
                btnSignature.Click += new EventHandler(btnSignature_Click);
                txtSignature.Text = Profile.Talks.Signature;
                ListView1.ItemDataBound += new EventHandler<ListViewItemEventArgs>(ListView1_ItemDataBound);
                ListView1.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListView1_ItemCommand);
                SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);
            }
        }

        SiteMapNode SiteMap_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);
            SiteMapNode tmpNode = currentNode;
            tmpNode.Title = _category.CategoryName;
            return currentNode;
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            SiteMap.SiteMapResolve -= new SiteMapResolveEventHandler(this.SiteMap_SiteMapResolve);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                page = int.Parse(Request.QueryString["page"]);
            }
            catch { page = 1; }
        }

        void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            switch (e.CommandName.ToLower())
            {
                case "sort":
                    Sort(e.CommandArgument.ToString());
                    break;
            }
        }

        void Sort(string pSortBy)
        {
            //LinqDataSource1.OrderBy = string.Format("IsRecommended desc, {0} desc", sortBy);
            ListView1.Sort(pSortBy, SortDirection.Descending);
            //sortBy = pSortBy + " desc";
        }

        void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            ThreadWithMainPost item = (ThreadWithMainPost)((ListViewDataItem)e.Item).DataItem;
            Panel hotPanel = (Panel)e.Item.FindControl("pnHot");
            int hotByRead = int.Parse(SiteConfig.ReadSetting(SiteConfigSection.Post, "HotThreadByReadCount"));
            int hotByReply = int.Parse(SiteConfig.ReadSetting(SiteConfigSection.Post, "HotThreadByReplyCount"));

            hotPanel.Visible = Convert.ToBoolean(item.IsHot) || hotByRead > 0 && item.ViewCount >= hotByRead || hotByReply > 0 && item.TotalPosts - 1 >= hotByReply;
        }

        void btnSignature_Click(object sender, EventArgs e)
        {
            Profile.Talks.Signature = txtSignature.Text;
            Profile.Save();
        }

        void lblBrowsing_PreRender(object sender, EventArgs e)
        {
            if (Request.QueryString["u"] != null && Request.QueryString["r"] == "1")
            {
                lblBrowsing.Text = "我参与的话题";
            }
            else if (Request.QueryString["u"] != null && Request.QueryString["r"] != "1")
            {
                lblBrowsing.Text = "我发起的话题";
            }
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            string q = string.Empty;

            if (Request.QueryString["r"] == "1")
            {
                if (Request.QueryString["u"] != null)
                {
                    e.Result = PostOperations.GetThreadListByReplyUserId(new Guid(Request.QueryString["u"]), this._cid);
                    //return;
                }
            }
            else
            {
                if (Request.QueryString["u"] != null)
                {
                    //e.Result = dataContext.GetThreads(_cid, new Guid(Request.QueryString["u"]), "", page, 0).ToList();
                    q = string.Format("EXEC GetThreads '{0}', '{1}', {2}, {3}, {4}", Request.QueryString["c"], Request.QueryString["u"],
                        Request.QueryString["by"] == null ? "'" + Request.QueryString["by"] + "'" : "null", page, "null"
                      );
                }
                else
                {
                    //e.Result = dataContext.GetThreads(_cid, null, Request.QueryString["by"] ?? "", page, 0).ToList();
                    q = string.Format("EXEC GetThreads '{0}', null, {2}, {3}, {4}", Request.QueryString["c"], "",
                        Request.QueryString["by"] != null ? "'" + Request.QueryString["by"] + "'" : "null", page, "null");
                     
                }

                using (scDataContext cxt = new scDataContext())
                {
                    e.Result = cxt.ExecuteQuery<ThreadWithMainPost>(q).ToList();
                }
            }

            //e.OrderByParameters["SortBy"] = sortBy;
        }

        protected void lnkCreateThread_PreRender(object sender, EventArgs e)
        {
            ((HyperLink)sender).NavigateUrl = string.Format("CreateThread.aspx?c={0}", Request.QueryString["c"]);
        }

        protected void lnkMyThreads_Init(object sender, EventArgs e)
        {
            ((HyperLink)sender).NavigateUrl = string.Format("Threads.aspx?c={0}&u={1}", Request.QueryString["c"], Profile.UserId);
        }

        protected void lnkMyReplies_Init(object sender, EventArgs e)
        {
            ((HyperLink)sender).NavigateUrl = string.Format("Threads.aspx?c={0}&u={1}&r=1", Request.QueryString["c"], Profile.UserId);
        }

        protected void lnkMySignature_Init(object sender, EventArgs e)
        {
        }

        protected void lnkAllThreads_Init(object sender, EventArgs e)
        {
            ((HyperLink)sender).NavigateUrl = string.Format("Threads.aspx?c={0}", Request.QueryString["c"]);
        }

        protected void GenerateOrderByLink(object sender, EventArgs e)
        {
            HyperLink link = (HyperLink)sender;
            try
            {
                if (Request.QueryString["by"] == link.Attributes["rel"])
                    link.CssClass = "sorted";
            }
            catch { }
            
            link.NavigateUrl = Request.Url.AbsolutePath + "?" + MakeQueryString(link.Attributes["rel"]);
        }

        string MakeQueryString(string by)
        {
            NameValueCollection tmp = new NameValueCollection(Request.QueryString);
            try
            {
                tmp.Remove("by");
            }
            catch { }

            tmp.Add("by", by);
            List<string> c = new List<string>();
            for (int i = 0; i < tmp.Count; i++)
            {
                c.Add(string.Format("{0}={1}", tmp.Keys[i], tmp[i]));
            }

            return string.Join("&", c.ToArray());
        }
    }
}
